const express = require('express');
const cors = require('cors');
const Docker = require('dockerode');
const rateLimit = require('express-rate-limit');
const containerRoutes = require('./routes/containers');
const imageRoutes = require('./routes/images');
const composeRoutes = require('./routes/compose');
const systemRoutes = require('./routes/system');

const app = express();
const docker = new Docker();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100 // 限制每个IP 15分钟内最多100个请求
});
app.use(limiter);

// 将docker实例传递给路由
app.use((req, res, next) => {
  req.docker = docker;
  next();
});

// 路由
app.use('/api/containers', containerRoutes);
app.use('/api/images', imageRoutes);
app.use('/api/compose', composeRoutes);
app.use('/api/system', systemRoutes);

// 错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器内部错误' });
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});
